package com.zhj.interview;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class Test06 {

    private static List<Integer> list = new ArrayList<>();
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {

        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    put(1);
                    put(2);
                    show();
                    System.out.println(get());
                    System.out.println(get());
                }
            };
            thread.start();
        }
    }

    private static void put(Integer num) {
        lock.lock();
        try {
            list.add(num);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static Integer get() {
        lock.lock();
        Integer result = null;
        try {
            result = list.get(list.size() - 1);
            list.remove(list.size()-1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return result;
    }

    private static void show() {
        lock.lock();
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println("队列内容：");
            System.out.print(iterator.next() + "\t");
        }
        System.out.println();
        lock.unlock();
    }
}
